const express = require('express');
const cors = require('cors');

const app = express();
const PORT = 8085;

// 中间件
app.use(cors({
  origin: ['http://localhost:5173', 'http://localhost:3000'],
  credentials: true
}));
app.use(express.json());

// 日志中间件
app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);
  console.log('Headers:', req.headers);
  console.log('Body:', req.body);
  next();
});

// 测试根路径
app.get('/', (req, res) => {
  res.json({
    message: 'HousingHub Test Backend Server',
    status: 'running',
    timestamp: new Date().toISOString()
  });
});

// 健康检查
app.get('/health', (req, res) => {
  res.json({
    status: 'healthy',
    port: PORT,
    timestamp: new Date().toISOString()
  });
});

// HousingHub API 路由
app.get('/housingHub', (req, res) => {
  res.json({
    message: 'HousingHub API Base',
    status: 'running',
    timestamp: new Date().toISOString()
  });
});

// 发送验证码接口
app.post('/housingHub/user/send-code', (req, res) => {
  const { email } = req.body;
  
  console.log('收到发送验证码请求:', { email });
  
  if (!email) {
    return res.status(400).json({
      code: '400',
      message: '邮箱地址不能为空',
      data: null
    });
  }
  
  // 模拟验证码发送
  const verificationCode = Math.floor(100000 + Math.random() * 900000);
  
  res.json({
    code: '200',
    message: '验证码发送成功',
    data: {
      email: email,
      verificationCode: verificationCode, // 实际项目中不应该返回验证码
      timestamp: new Date().toISOString()
    }
  });
});

// 用户注册接口
app.post('/housingHub/user/register', (req, res) => {
  const { username, email, password, confirmPassword, verificationCode } = req.body;
  
  console.log('收到用户注册请求:', { username, email, verificationCode });
  
  // 简单验证
  if (!username || !email || !password || !confirmPassword || !verificationCode) {
    return res.status(400).json({
      code: '400',
      message: '请填写完整的注册信息',
      data: null
    });
  }
  
  if (password !== confirmPassword) {
    return res.status(400).json({
      code: '400',
      message: '两次输入的密码不一致',
      data: null
    });
  }
  
  // 模拟注册成功
  res.json({
    code: '200',
    message: '注册成功',
    data: {
      userId: Math.floor(10000 + Math.random() * 90000),
      username: username,
      email: email,
      timestamp: new Date().toISOString()
    }
  });
});

// 用户登录接口
app.post('/housingHub/user/login', (req, res) => {
  const { email, password } = req.body;
  
  console.log('收到用户登录请求:', { email });
  
  if (!email || !password) {
    return res.status(400).json({
      code: '400',
      message: '邮箱和密码不能为空',
      data: null
    });
  }
  
  // 模拟登录成功
  res.json({
    code: '200',
    message: '登录成功',
    data: {
      token: 'test-token-' + Date.now(),
      userInfo: {
        userId: 12345,
        username: 'testuser',
        email: email
      },
      timestamp: new Date().toISOString()
    }
  });
});

// 管理员登录接口
app.post('/housingHub/admin/login', (req, res) => {
  const { username, password } = req.body;

  console.log('🔔 收到管理员登录请求:', { username });

  if (!username || !password) {
    return res.status(400).json({
      code: '400',
      message: '用户名和密码不能为空',
      data: null
    });
  }

  // 简单的管理员验证（实际项目中应该查询数据库）
  if (username === 'admin' && password === 'admin123') {
    console.log(`✅ 管理员登录成功: ${username}`);

    res.json({
      code: '200',
      message: '登录成功',
      data: {
        token: 'admin-token-' + Date.now(),
        adminInfo: {
          adminId: 1,
          username: username,
          role: 'admin'
        },
        timestamp: new Date().toISOString()
      }
    });
  } else {
    res.status(401).json({
      code: '401',
      message: '用户名或密码错误',
      data: null
    });
  }
});

// 模拟房产认证数据
const mockPropertyVerifications = [
  {
    propertyVerifyId: 1,
    userId: 10001,
    propertyAddr: '北京市朝阳区三里屯街道工体北路8号',
    propertyNo: 'BJ2023001234567',
    propertyPicPath: 'https://via.placeholder.com/400x300/4CAF50/FFFFFF?text=Property+Certificate+1',
    applyTime: '2024-01-15 10:30:00',
    verifyStatus: 0,
    refuseReason: null
  },
  {
    propertyVerifyId: 2,
    userId: 10002,
    propertyAddr: '上海市浦东新区陆家嘴环路1000号',
    propertyNo: 'SH2023002345678',
    propertyPicPath: 'https://via.placeholder.com/400x300/2196F3/FFFFFF?text=Property+Certificate+2',
    applyTime: '2024-01-16 14:20:00',
    verifyStatus: 1,
    refuseReason: null
  },
  {
    propertyVerifyId: 3,
    userId: 10003,
    propertyAddr: '广州市天河区珠江新城花城大道123号',
    propertyNo: 'GZ2023003456789',
    propertyPicPath: 'https://via.placeholder.com/400x300/FF9800/FFFFFF?text=Property+Certificate+3',
    applyTime: '2024-01-17 09:15:00',
    verifyStatus: 2,
    refuseReason: '房产证信息不清晰，请重新上传'
  },
  {
    propertyVerifyId: 4,
    userId: 10004,
    propertyAddr: '深圳市南山区科技园南区深南大道9999号',
    propertyNo: 'SZ2023004567890',
    propertyPicPath: 'https://via.placeholder.com/400x300/9C27B0/FFFFFF?text=Property+Certificate+4',
    applyTime: '2024-01-18 16:45:00',
    verifyStatus: 0,
    refuseReason: null
  },
  {
    propertyVerifyId: 5,
    userId: 10005,
    propertyAddr: '杭州市西湖区文三路259号',
    propertyNo: 'HZ2023005678901',
    propertyPicPath: 'https://via.placeholder.com/400x300/F44336/FFFFFF?text=Property+Certificate+5',
    applyTime: '2024-01-19 11:30:00',
    verifyStatus: 1,
    refuseReason: null
  }
];

// 获取所有房产认证信息
app.get('/housingHub/admin/house/getAllPropertyVerification', (req, res) => {
  console.log('🔔 收到获取房产认证列表请求');

  // 检查管理员token（简单验证）
  const token = req.headers['info'];
  if (!token || !token.includes('admin-token')) {
    return res.status(401).json({
      code: '401',
      message: '未授权访问',
      data: null
    });
  }

  console.log(`✅ 返回 ${mockPropertyVerifications.length} 条房产认证记录`);

  res.json({
    code: '200',
    message: '获取成功',
    data: mockPropertyVerifications
  });
});

// 通过房产认证
app.post('/housingHub/admin/house/passVerify/:propertyVerifyId', (req, res) => {
  const propertyVerifyId = parseInt(req.params.propertyVerifyId);

  console.log('🔔 收到通过房产认证请求:', { propertyVerifyId });

  // 检查管理员token
  const token = req.headers['info'];
  if (!token || !token.includes('admin-token')) {
    return res.status(401).json({
      code: '401',
      message: '未授权访问',
      data: null
    });
  }

  // 查找并更新认证状态
  const verification = mockPropertyVerifications.find(v => v.propertyVerifyId === propertyVerifyId);
  if (verification) {
    verification.verifyStatus = 1;
    verification.refuseReason = null;

    console.log(`✅ 房产认证 ${propertyVerifyId} 已通过`);

    res.json({
      code: '200',
      message: '审核通过',
      data: verification
    });
  } else {
    res.status(404).json({
      code: '404',
      message: '房产认证记录不存在',
      data: null
    });
  }
});

// 批量通过房产认证
app.post('/housingHub/admin/house/batchPassVerify', (req, res) => {
  const propertyVerifyIds = req.body;

  console.log('🔔 收到批量通过房产认证请求:', { propertyVerifyIds });

  // 检查管理员token
  const token = req.headers['info'];
  if (!token || !token.includes('admin-token')) {
    return res.status(401).json({
      code: '401',
      message: '未授权访问',
      data: null
    });
  }

  if (!Array.isArray(propertyVerifyIds) || propertyVerifyIds.length === 0) {
    return res.status(400).json({
      code: '400',
      message: '请提供有效的认证ID列表',
      data: null
    });
  }

  // 批量更新认证状态
  let updatedCount = 0;
  propertyVerifyIds.forEach(id => {
    const verification = mockPropertyVerifications.find(v => v.propertyVerifyId === id);
    if (verification) {
      verification.verifyStatus = 1;
      verification.refuseReason = null;
      updatedCount++;
    }
  });

  console.log(`✅ 批量通过 ${updatedCount} 个房产认证`);

  res.json({
    code: '200',
    message: `成功通过 ${updatedCount} 个房产认证`,
    data: { updatedCount }
  });
});

// 拒绝房产认证
app.post('/housingHub/admin/house/rejectPropertyVerification/:propertyVerifyId', (req, res) => {
  const propertyVerifyId = parseInt(req.params.propertyVerifyId);
  const reason = req.body;

  console.log('🔔 收到拒绝房产认证请求:', { propertyVerifyId, reason });

  // 检查管理员token
  const token = req.headers['info'];
  if (!token || !token.includes('admin-token')) {
    return res.status(401).json({
      code: '401',
      message: '未授权访问',
      data: null
    });
  }

  if (!reason || reason.trim() === '') {
    return res.status(400).json({
      code: '400',
      message: '拒绝原因不能为空',
      data: null
    });
  }

  // 查找并更新认证状态
  const verification = mockPropertyVerifications.find(v => v.propertyVerifyId === propertyVerifyId);
  if (verification) {
    verification.verifyStatus = 2;
    verification.refuseReason = reason;

    console.log(`✅ 房产认证 ${propertyVerifyId} 已拒绝，原因: ${reason}`);

    res.json({
      code: '200',
      message: '审核已拒绝',
      data: verification
    });
  } else {
    res.status(404).json({
      code: '404',
      message: '房产认证记录不存在',
      data: null
    });
  }
});

// 根据用户ID获取房产认证信息（房东接口）
app.get('/housingHub/landlord/getPropertyVerificationByUserId/:userId', (req, res) => {
  const userId = parseInt(req.params.userId);

  console.log('🔔 收到获取用户房产认证请求:', { userId });

  // 检查用户token
  const token = req.headers['info'];
  if (!token) {
    return res.status(401).json({
      code: '401',
      message: '未授权访问',
      data: null
    });
  }

  // 根据用户ID过滤房产认证数据
  const userVerifications = mockPropertyVerifications.filter(v => v.userId === userId);

  console.log(`✅ 返回用户 ${userId} 的 ${userVerifications.length} 条房产认证记录`);

  res.json({
    code: '200',
    message: '获取成功',
    data: userVerifications
  });
});

// 根据房产证编号获取拒绝原因（房东接口）
app.get('/housingHub/landlord/getPropertyVerifyRefuseReasonByPropertyNo/:propertyNo', (req, res) => {
  const propertyNo = req.params.propertyNo;

  console.log('🔔 收到获取拒绝原因请求:', { propertyNo });

  // 检查用户token
  const token = req.headers['info'];
  if (!token) {
    return res.status(401).json({
      code: '401',
      message: '未授权访问',
      data: null
    });
  }

  // 查找对应的房产认证记录
  const verification = mockPropertyVerifications.find(v => v.propertyNo === propertyNo);

  if (verification) {
    if (verification.verifyStatus === 2 && verification.refuseReason) {
      console.log(`✅ 返回房产证 ${propertyNo} 的拒绝原因: ${verification.refuseReason}`);

      res.json({
        code: '200',
        message: '获取成功',
        data: verification.refuseReason
      });
    } else {
      res.json({
        code: '200',
        message: '该房产认证未被拒绝或无拒绝原因',
        data: null
      });
    }
  } else {
    res.status(404).json({
      code: '404',
      message: '未找到对应的房产认证记录',
      data: null
    });
  }
});

// 取消房产认证（房东接口）
app.post('/housingHub/landlord/cancelVerification/:userId/:propertyVerifyId', (req, res) => {
  const userId = parseInt(req.params.userId);
  const propertyVerifyId = parseInt(req.params.propertyVerifyId);

  console.log('🔔 收到取消房产认证请求:', { userId, propertyVerifyId });

  // 检查用户token
  const token = req.headers['info'];
  if (!token) {
    return res.status(401).json({
      code: '401',
      message: '未授权访问',
      data: null
    });
  }

  // 查找并删除认证记录
  const index = mockPropertyVerifications.findIndex(v =>
    v.propertyVerifyId === propertyVerifyId && v.userId === userId
  );

  if (index !== -1) {
    const verification = mockPropertyVerifications[index];

    // 只允许删除已驳回或已取消的认证
    if (verification.verifyStatus === 2 || verification.verifyStatus === 3) {
      mockPropertyVerifications.splice(index, 1);

      console.log(`✅ 已删除房产认证 ${propertyVerifyId}`);

      res.json({
        code: '200',
        message: '删除成功',
        data: null
      });
    } else {
      res.status(400).json({
        code: '400',
        message: '只能删除已驳回或已取消的房产认证',
        data: null
      });
    }
  } else {
    res.status(404).json({
      code: '404',
      message: '未找到对应的房产认证记录',
      data: null
    });
  }
});

// 批量取消房产认证（房东接口）
app.post('/housingHub/landlord/cancelBatchVerification/:userId', (req, res) => {
  const userId = parseInt(req.params.userId);
  const propertyVerifyIds = req.body;

  console.log('🔔 收到批量取消房产认证请求:', { userId, propertyVerifyIds });

  // 检查用户token
  const token = req.headers['info'];
  if (!token) {
    return res.status(401).json({
      code: '401',
      message: '未授权访问',
      data: null
    });
  }

  if (!Array.isArray(propertyVerifyIds) || propertyVerifyIds.length === 0) {
    return res.status(400).json({
      code: '400',
      message: '请提供有效的认证ID列表',
      data: null
    });
  }

  let deletedCount = 0;

  // 批量删除认证记录
  for (let i = mockPropertyVerifications.length - 1; i >= 0; i--) {
    const verification = mockPropertyVerifications[i];

    if (propertyVerifyIds.includes(verification.propertyVerifyId) &&
        verification.userId === userId &&
        (verification.verifyStatus === 2 || verification.verifyStatus === 3)) {
      mockPropertyVerifications.splice(i, 1);
      deletedCount++;
    }
  }

  console.log(`✅ 批量删除 ${deletedCount} 个房产认证`);

  res.json({
    code: '200',
    message: `成功删除 ${deletedCount} 个房产认证`,
    data: { deletedCount }
  });
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error('服务器错误:', err);
  res.status(500).json({
    code: '500',
    message: '服务器内部错误',
    data: null
  });
});

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    code: '404',
    message: '接口不存在',
    path: req.originalUrl,
    timestamp: new Date().toISOString()
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log('='.repeat(80));
  console.log(`🚀 HousingHub Test Backend Server 启动成功!`);
  console.log(`📍 服务地址: http://localhost:${PORT}`);
  console.log(`🔗 API基础路径: http://localhost:${PORT}/housingHub`);
  console.log('');
  console.log('📋 用户接口:');
  console.log(`  📧 验证码接口: POST http://localhost:${PORT}/housingHub/user/send-code`);
  console.log(`  👤 注册接口: POST http://localhost:${PORT}/housingHub/user/register`);
  console.log(`  🔑 登录接口: POST http://localhost:${PORT}/housingHub/user/login`);
  console.log('');
  console.log('🔧 管理员接口:');
  console.log(`  🔐 管理员登录: POST http://localhost:${PORT}/housingHub/admin/login`);
  console.log(`  🏠 获取房产认证: GET http://localhost:${PORT}/housingHub/admin/house/getAllPropertyVerification`);
  console.log(`  ✅ 通过认证: POST http://localhost:${PORT}/housingHub/admin/house/passVerify/:id`);
  console.log(`  📦 批量通过: POST http://localhost:${PORT}/housingHub/admin/house/batchPassVerify`);
  console.log(`  ❌ 拒绝认证: POST http://localhost:${PORT}/housingHub/admin/house/rejectPropertyVerification/:id`);
  console.log('');
  console.log('🏡 房东接口:');
  console.log(`  📋 获取我的认证: GET http://localhost:${PORT}/housingHub/landlord/getPropertyVerificationByUserId/:userId`);
  console.log(`  ❓ 查询拒绝原因: GET http://localhost:${PORT}/housingHub/landlord/getPropertyVerifyRefuseReasonByPropertyNo/:propertyNo`);
  console.log(`  🗑️ 删除认证: POST http://localhost:${PORT}/housingHub/landlord/cancelVerification/:userId/:propertyVerifyId`);
  console.log(`  📦 批量删除: POST http://localhost:${PORT}/housingHub/landlord/cancelBatchVerification/:userId`);
  console.log('');
  console.log(`⏰ 启动时间: ${new Date().toISOString()}`);
  console.log('='.repeat(80));
  console.log('📝 等待API请求...\n');
});

// 优雅关闭
process.on('SIGINT', () => {
  console.log('\n🛑 正在关闭服务器...');
  process.exit(0);
});

process.on('SIGTERM', () => {
  console.log('\n🛑 正在关闭服务器...');
  process.exit(0);
});
